const request = require('../../utils/request')
const eventBus = require('../../utils/eventBus')
const analytics = require('../../utils/analytics')  // 引入埋点模块

Page({
  data: {
    bookings: [],
    filteredBookings: [],
    showRatingModal: false,
    currentBooking: null,
    ratingValue: 0,
    commentValue: '',
    scrollHeight: 0,
    activeTab: 'all'
  },

  onLoad() {
    this.fetchBookings()
    eventBus.on('bookingCreated', this.fetchBookings.bind(this))
    
    const systemInfo = wx.getSystemInfoSync()
    const navHeight = 44
    const statusBarHeight = systemInfo.statusBarHeight
    const scrollHeight = systemInfo.windowHeight - (navHeight + statusBarHeight + 44) // 44px为页签高度
    
    this.setData({
      scrollHeight: scrollHeight
    })
    
    // 记录页面浏览埋点
    analytics.pageView('booking_history', {
      view_type: 'all'
    })
  },

  onUnload() {
    eventBus.off('bookingCreated', this.fetchBookings)
  },

  // 切换页签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    
    this.setData({
      activeTab: tab
    })
    
    // 根据选中的页签筛选数据
    this.filterBookings()
  },
  
  // 根据当前选中的页签筛选预约数据
  filterBookings() {
    const { bookings, activeTab } = this.data
    
    if (activeTab === 'all') {
      this.setData({
        filteredBookings: bookings
      })
      return
    }
    
    const filtered = bookings.filter(booking => booking.status === activeTab)
    this.setData({
      filteredBookings: filtered
    })
  },

  async fetchBookings() {
    try {
      // 获取当前用户ID
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      const userId = app.globalData.userInfo.id;
      
      const response = await request({
        url: '/api/bookings',
        data: { userId }
      })

      const now = new Date()
      const processedBookings = []
      
      for (let i = 0; i < response.data.length; i++) {
        const booking = response.data[i]
        const timeSlots = booking.course_time.split('-')
        const startTime = timeSlots[0]
        const endTime = timeSlots[1]
        const date = booking.formatted_date
        
        const bookingStartTime = new Date(date.replace(/-/g, '/') + ' ' + startTime)
        const bookingEndTime = new Date(date.replace(/-/g, '/') + ' ' + endTime)
        
        let status = booking.status
        if (status !== 'cancelled') {
          if (now < bookingStartTime) {
            status = 'upcoming'
          } else if (now >= bookingStartTime && now <= bookingEndTime) {
            status = 'ongoing'
          } else {
            status = 'completed'
          }
        }

        const processedBooking = {
          id: booking.id,
          course_id: booking.course_id,
          course_name: booking.course_name,
          formatted_date: booking.formatted_date,
          course_time: booking.course_time,
          teacher_name: booking.teacher_name,
          cover: booking.cover,
          status: status,
          rating: booking.rating || 0,
          comment: booking.comment || '',
          is_rated: booking.is_rated
        }
        
        processedBookings.push(processedBooking)
      }

      this.setData({ 
        bookings: processedBookings
      }, () => {
        // 更新筛选后的数据
        this.filterBookings()
      })
    } catch (error) {
      console.error('获取预约记录失败:', error)
      wx.showToast({
        title: '获取预约记录失败',
        icon: 'none'
      })
    }
  },

  navigateToCourse(e) {
    const { courseId } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/packageA/course-detail/index?id=${courseId}`
    })
  },

  openRatingModal(e) {
    const booking = e.currentTarget.dataset.booking
    this.setData({
      showRatingModal: true,
      currentBooking: booking,
      ratingValue: 0,
      commentValue: '',
      isEditing: false
    })
    
    // 添加埋点 - 打开评分弹窗
    analytics.track('click', parseInt(booking.course_id), {
      element_id: 'rating_modal_open',
      page_name: 'booking_history',
      booking_id: booking.id
    })
  },

  editRating(e) {
    const booking = e.currentTarget.dataset.booking
    this.setData({
      showRatingModal: true,
      currentBooking: booking,
      ratingValue: booking.rating || 0,
      commentValue: booking.comment || '',
      isEditing: true
    })
    
    // 添加埋点 - 编辑评分
    analytics.track('click', parseInt(booking.course_id), {
      element_id: 'rating_modal_edit',
      page_name: 'booking_history',
      booking_id: booking.id,
      previous_rating: booking.rating
    })
  },

  async submitRating() {
    if (this.data.ratingValue === 0) {
      wx.showToast({
        title: '请选择评分',
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: '提交中...' })

    try {
      // 获取当前用户ID
      const app = getApp();
      const userId = app.globalData.userInfo?.id;
      if (!userId) {
        wx.hideLoading();
        wx.showToast({
          title: '登录状态异常',
          icon: 'none'
        });
        return;
      }
      
      const courseId = this.data.currentBooking.course_id

      await request({
        url: '/api/bookings/rate',
        method: 'POST',
        data: {
          bookingId: this.data.currentBooking.id,
          rating: this.data.ratingValue,
          comment: this.data.commentValue,
          isUpdate: this.data.isEditing,
          userId,
          shouldAddPoints: !this.data.isEditing  // 只在第一次评价时增加积分
        }
      })
      
      // 如果是第一次评价，触发积分更新事件
      if (!this.data.isEditing) {
        eventBus.emit('pointsUpdate')
      }
        wx.showToast({
          title: '评价成功',
          icon: 'success'
        })
      
      // 添加埋点 - 提交评分
      analytics.rateCourse(
        parseInt(courseId), 
        this.data.ratingValue, 
        this.data.commentValue
      )
      
      // 使用更通用的track方法记录更多详情
      analytics.track('rate', parseInt(courseId), {
        rating: this.data.ratingValue,
        comment: this.data.commentValue,
        is_update: this.data.isEditing,
        booking_id: this.data.currentBooking.id,
        source: 'booking_history',
        course_name: this.data.currentBooking.course_name
      })

      await this.fetchBookings()

      this.setData({
        showRatingModal: false,
        currentBooking: null,
        ratingValue: 0,
        commentValue: '',
        isEditing: false
      })

      wx.hideLoading()

      eventBus.emit('commentUpdated', {
        courseId: courseId
      })
    } catch (error) {
      console.error('评价失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: error.message || '评价失败',
        icon: 'none'
      })
    }
  },

  closeRatingModal() {
    this.setData({
      showRatingModal: false,
      currentBooking: null,
      ratingValue: 0,
      commentValue: ''
    })
  },

  onRatingChange(e) {
    this.setData({
      ratingValue: e.detail.value
    })
  },

  onCommentInput(e) {
    this.setData({
      commentValue: e.detail.value
    })
  },

  onBack() {
    wx.navigateBack()
  },

  // 添加导航到首页的方法
  navigateToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  setRating(e) {
    const rating = parseInt(e.currentTarget.dataset.rating)
    this.setData({
      ratingValue: rating
    })
    
    // 添加埋点 - 选择评分等级
    if (this.data.currentBooking) {
      analytics.track('click', parseInt(this.data.currentBooking.course_id), {
        element_id: 'rating_select',
        rating_value: rating,
        page_name: 'booking_history',
        is_editing: this.data.isEditing
      })
    }
  }
})